#ifndef TYPETRANSFER_H
#define TYPETRANSFER_H
#include <string.h>
#include <boost/array.hpp>
template<typename T>
class TypeTransfer
{
public:
    TypeTransfer();
public:
    static void Type2ByteArray(void *dst,const T d,size_t len=0)
    {
        Data data(d);
        char *arr=static_cast<char*>(dst);
        if(len==0)
            len=sizeof (T);
        else
            len=sizeof (T)>len?len:sizeof (T);
        if(IsBigEndian())
        {
            for (size_t i=0;i<len;i++)
            {
                arr[i]=data.c[sizeof (data)-i-1];
            }
        }
        else
        {
            memcpy(dst,data.c,len);
        }
    }
    static void ByteArray2Type(T &d, const void *src,size_t len=0)
    {
        Data data;
        const char *arr=static_cast<const char*>(src);
        if(len==0)
            len=sizeof (T);
        else
            len=sizeof (T)>len?len:sizeof (T);
        if(IsBigEndian())
        {
            for (size_t i=0;i<len;i++)
            {
                data.c[sizeof (data)-i-1]=arr[i];
            }
        }
        else
        {
             memcpy(data.c,src,len);
        }
        d=data.d;
    }
    static void ByteArray2Type(T &d, const boost::array<u_char,1024> &src, size_t start=0, size_t len=0)
    {
        Data data;
        //const char *arr=static_cast<const char*>(src);
        if(len==0)
            len=sizeof (T);
        else
            len=sizeof (T)>len?len:sizeof (T);
        if(IsBigEndian())
        {
            for (size_t i=start;i<start+len;i++)
            {
                data.c[sizeof (data)-i-1]=src[i];
            }
        }
        else
        {
             memcpy(data.c,&src[start],len);
        }
        d=data.d;
    }
private:
    union Data{
        T d;
        char c[sizeof (T)];
        Data(const T data):d(data){}
        Data(){}
    };
    static bool IsBigEndian()
    {
        static bool init=false;
        static bool is_big_endian=false;
        if(init)
            return is_big_endian;

        union NUM
        {
            int a;
            char b;
        }num;
        num.a = 0x1234;
        if( num.b == 0x12 )
            is_big_endian=true;
        else
            is_big_endian=false;
        init=true;
        return is_big_endian;
    }
};


#endif // TYPETRANSFER_H
